import pool from '../db/index';
import { getQuery } from 'h3';

export default defineEventHandler(async (event) => {
  try {
    // 获取数据库连接
    const connection = await pool.getConnection();
    try {
      // 测试查询
      // 获取分页参数，默认第1页，每页10条
      const { page = 1, pageSize = 10 } = getQuery(event);
      const offset = (Number(page) - 1) * Number(pageSize);

      // 1. 查询总数
      const [countResult] = await connection.execute('SELECT COUNT(*) as total FROM song');
      const total = (countResult as {total:number}[])[0].total;

      // 2. 分页查询数据
      const [rows] = await connection.execute(
        'SELECT * FROM song LIMIT ? OFFSET ?',
        [Number(pageSize), offset]
      );

      return {
        status: 'success',
        data: rows,
        pagination: {
          total,
          page: Number(page),
          pageSize: Number(pageSize),
          totalPages: Math.ceil(total / Number(pageSize))
        }
      };
    } finally {
      // 确保连接始终释放
      connection.release();
    }
  } catch (error) {
    console.error('数据库连接失败:', error);
    return {
      status: 'error',
      message: '数据库连接失败',
      error: error instanceof Error ? error.message : String(error)
    };
  }
});